<template>
	<view class="container">
		<tui-navigation-bar opacity="0" @init="initNavigation" :scrollTop="scrollTop" backgroundColor="#fff"
			color="#333">
			<view class="tui-header" :style="{ marginTop: navBarTop + 'px' }">
				<view class="title">
					<text class="txt">消息</text>
				</view>
			</view>
		</tui-navigation-bar>
		<view class="main">
			<!-- <view class="advertising" v-if="isBuy == 0"@tap.stop.prevent="lookOver(isBuy)"></view> -->
			<!-- <button class="advertising" v-else open-type="contact"> </button> -->
			<view class="message-list" v-if="conversationList.length > 0">
				<tui-swipe-action :actions="options" @click="removeMessage($event,item)"
					v-for="(item,index) in conversationList" :key="index" :params="item" :open="item.actionShow"
					@btnClose="btnClose" :forbid="['C2C10087','C2C10088','C2C10089'].includes(item.conversationID)">
					<template v-slot:content>
						<view class="message-view" @click="handleSwitchConversation(item.conversationID)">
							<view class="message-item">
								<image class="avatar" :class="{'system-avatar':item.conversationID == 'C2C10089'}"
									v-if="!['C2C10087','C2C10088'].includes(item.conversationID)"
									:src="item.userProfile.avatar" mode="aspectFill"></image>
								<image class="avatar" v-else-if="item.conversationID == 'C2C10088'"
									src="https://pengtou-1322587508.cos.ap-shanghai.myqcloud.com/static/images/community/comment1.png"
									mode="aspectFill"></image>
								<image class="avatar" v-else-if="item.conversationID == 'C2C10087'"
									src="https://pengtou-1322587508.cos.ap-shanghai.myqcloud.com/static/images/community/like1.png"
									mode="aspectFill"></image>
								<view class="message">
									<view class="name">{{item.userProfile.nick}}</view>
									<view v-if="item.lastMessage.type != 'TIMCustomElem'"
										class="content onelist-hidden">{{item.lastMessage.messageForShow}}</view>
									<view v-else class="content onelist-hidden">
										{{item.lastMessage.payload.data | customMessage}}
									</view>
								</view>
								<view class="statue">
									<view class="time">{{ item.lastMessage.lastTime | timeFormats}}</view>
									<view class="count" v-if="item.unreadCount > 0">{{item.unreadCount}}</view>
								</view>
							</view>
						</view>
					</template>
				</tui-swipe-action>
			</view>
			<view v-show="conversationList.length <= 0">
				<empty fixed></empty>
			</view>
			<view v-show="load.loading">
				<uv-load-more :status="load.status" :loading-text="load.loadingText" :nomore-text="load.nomoreText"
					:line="load.status == 'nomore'" />
			</view>
		</view>
		<!-- #ifdef MP -->
		<addition-MP></addition-MP>
		<!-- #endif -->
		<survey-pop></survey-pop>
		<tabbar :current="tabbarCurrent" backdropFilter :tabBar="tabBar"></tabbar>
	</view>
</template>

<script>
	import mp from "@/mixins/mp.js";
	import {
		mapState
	} from "vuex";
	import tabbar from '@/components/custom-tabbar/custom-tabbar.vue';
	import {
		timeFormat,
		timeFrom
	} from '@/uni_modules/uv-ui-tools/libs/function/index.js';
	const app = getApp();
	export default {
		mixins: [mp],
		options: {
			styleIsolation: 'shared'
		}, //解决/deep/不生效**
		components: {
			tabbar,
		},
		data() {
			return {
				tabbarCurrent: 2, //当前索引
				tabBar: app.globalData.tabBar,
				navBarOpacity: 0, //标题图标距离顶部距离
				scrollTop: 0.5, //页面滚动高度
				navBarTop: 0, // 导航栏content顶部m-top
				skeletonShow: true, //加载框
				pageTitle: '', //标题
				unread: 0,
				options: [{
					name: '删除',
					color: '#fff',
					fontsize: 30, //单位rpx
					width: 70, //单位px
					background: '#FF4664'
				}],
				messageList: {
					list: [],
					hasMore: false,
					loading: false,
					page: 1,
				},
				load: {
					loading: false,
					status: 'loading',
					loadingText: '努力加载中',
					nomoreText: '没有更多了'
				},
				tabs: {
					list: [{
						id: 'place',
						name: '我的下单',
					}, {
						id: 'receiv',
						name: '我的接单',
					}],
					current: 'place'
				},
				isBuy: 0,
				messageTabs: {
					list: [{
						id: 'all',
						name: '全部',
						data: 0,
					}, {
						id: 'await',
						name: '待接单',
						data: 1,
					}, {
						id: 'underway',
						name: '进行中',
						data: 2,
					}, {
						id: 'complete',
						name: '已完成',
						data: 3,
					}, {
						id: 'cancel',
						name: '已取消',
						data: -1,
					}],
					current: 'all'
				},
			};
		},
		/**
		 * 计算属性
		 */
		computed: {
			...mapState({
				isLogin: state => state.isLogin,
				isSDKReady: state => state.isSDKReady,
				conversationList: state => state.conversationList,
			})
		},
		watch: {
			isSDKReady(val) {
				//isSDKReady == true 
				if (val) {
					//更新用户自己的基础资料（头像+昵称+个性签名）
					this.updateUserInfo()
					//请求会话列表
					this.getConversationList()
				}
			},
		},
		filters: {
			timeFormats: function(value) {
				if (value == 0 || !value) {
					return ''
				} else {
					return timeFrom(value * 1000, false)
				}
			},
			customMessage: function(value) {
				switch (value) {
					case 'telephone':
						return '[系统通知]'
				}
			},
		},
		onLoad(options) {
			// uni.$TUIKit.on(uni.$TUIKitEvent.CONVERSATION_LIST_UPDATED, this.$convListUpdate, this);
		},
		onShow: function() {
			if (!app.globalData.isLogin) {
				app.doLogin()
				return
			}
			this.couponDetail = uni.getStorageSync('coupon_detail') ? uni.getStorageSync('coupon_detail') : {};
			if (this.couponDetail && this.couponDetail.userCouponId) {
				this.isBuy = 1
			}
			this.getConversationList()
			app.globalData.tabBar[0].name = 'active-home'
		},
		/**
		 * 下拉
		 */
		onPullDownRefresh: function() {
			this.messageList.page = 1
		},
		/**
		 * 触底
		 */
		onReachBottom() {
			if (this.messageList.hasMore && this.messageList.loading) {
				this.load.loading = true
				// this.getPageData()
			}
		},
		/**
		 * 滚动
		 */
		onPageScroll(res) {
			this.scrollTop = res.scrollTop;
		},
		methods: {
			//获取消息列表
			getConversationList() {
				// 拉取会话列表
				let promise = uni.$TUIKit.getConversationList();
				promise.then((res) => {
					console.log(res);
					let conversationList = res.data.conversationList; // 会话列表，用该列表覆盖原有的会话列表
					if (conversationList.length) {
						//将返回的会话列表拼接上 用户的基本资料  
						//说明：如果已经将用户信息 提交到tim服务端了 就不需要再次拼接
						conversationList.forEach((item, index) => {
							item.actionShow = false
						})
						this.$store.commit("updateConversationList", conversationList);
						console.log(conversationList);
					}
				}).catch((err) => {
					console.warn('getConversationList error:', err); // 获取会话列表失败的相关信息
				});
			},
			//提交用户的基础信息到Im
			updateUserInfo() {
				//将已经登陆的用户信息 提交到IM中
				let userInfo = uni.getStorageSync('user_info')
				let promise = uni.$TUIKit.updateMyProfile({
					nick: userInfo.authInfo.name,
					avatar: userInfo.avatarUrl,
					selfSignature: '暂无个性签名',
				});
				promise.then((res) => {
					console.log('提交资料成功')
				}).catch((err) => {
					console.warn('updateMyProfile error:', imError); // 更新资料失败的相关信息
				});
			},
			goLogin() {
				app.doLogin()
			},
			btnClose() {
				this.options[0].name = '删除'
			},
			lookOver(buy) {
				uni.navigateTo({
					url: '/page_account/advertising/advertising?isBuy=' + buy
				})
			},
			removeMessage(e, item) {
				if (this.options[e.index].name == '删除') {
					item.actionShow = false
					setTimeout(() => {
						this.options[e.index].name = '确认删除'
						item.actionShow = true
					}, 200)
					return
				}
				return
				let promise = uni.$TUIKit.deleteConversation({
					conversationIDList: [item.conversationID],
					clearHistoryMessage: false
				});
				promise.then(function(imResponse) {
					// 删除会话成功
					const {
						conversationIDList
					} = imResponse.data; // 被删除的会话 ID 列表
					this.options[e.index].name = '删除'
					this.getConversationList()
				}).catch(function(imError) {
					console.warn('deleteConversation error:', imError); // 删除会话失败的相关信息
				});
			},
			handleSwitchConversation(userId) {
				this.$store.commit('createConversationActive', userId)
				if (userId == 'C2C10089') {
					uni.navigateTo({
						url: "/page_chat/chat/chat?conversationID=" + userId
					})
				} else if (userId == 'C2C10088') {
					uni.navigateTo({
						url: "/page_community/notification/comment?conversationID=" + userId
					})
				} else if (userId == 'C2C10087') {
					uni.navigateTo({
						url: "/page_community/notification/like?conversationID=" + userId
					})
				} else {
					uni.navigateTo({
						url: "/page_chat/chat/chat?conversationID=" + userId
					})
				}

			},
			initNavigation(e) {
				this.navBarOpacity = e.opacity;
				this.navBarTop = e.top;
			},
			// 加载页面数据
			getPageData: function(callback) {
				Promise.all([]).then(() => {
					uni.stopPullDownRefresh();
					this.messageList.loading = true
				});
			},
			onAppraise(item) {
				uni.navigateTo({
					url: '/page_community/send/appraise?id=' + item.messageId
				})
			},

			// 返回上一页
			goBack: function() {
				app.beNavigateBack();
			},
		},
	};
</script>
<style lang="scss" scoped>
	.container {
		padding-bottom: 130rpx;
		min-height: 100vh;
		width: 100vw;
		background: url('https://pengtou-1322587508.cos.ap-shanghai.myqcloud.com/static/images/community/order-header.png');
		background-repeat: no-repeat;
		background-size: 100VW 202rpx;
		box-sizing: border-box;


		.tui-header {
			width: 100%;
			position: fixed;
			top: 0;
			display: flex;
			// align-items: center;
			align-items: normal;
			height: 32px;
			transform: translateZ(0);
			z-index: 99999;
			box-sizing: border-box;
			flex-direction: column;

			.get-back {
				flex-shrink: 0;
				width: 36rpx;
				height: 36rpx;
				color: #fff;
				// color: #000;
				font-size: 36rpx;
				padding: 2rpx 40rpx 2rpx 2rpx;
			}

			.title {
				box-sizing: border-box;
				padding-left: 48rpx;
				font-size: 48rpx;
				font-weight: 900;
				color: #222222;
				line-height: 32px;

				.txt {
					position: relative;
				}

				.txt::after {
					content: "";
					position: absolute;
					top: -20rpx;
					right: -20rpx;
					width: 30rpx;
					height: 30rpx;
					background: url(https://pengtou-1322587508.cos.ap-shanghai.myqcloud.com/static/images/share/star.png) 0 0/30rpx 30rpx no-repeat;
				}
			}

		}

		.main {
			box-sizing: border-box;
			padding: 214rpx 0 66rpx;
			padding-bottom: constant(safe-area-inset-bottom);
			padding-bottom: env(safe-area-inset-bottom);
			
			.advertising {
				width: 702rpx;
				height: 76rpx;
				// background: #E2F2C7;
				padding: 0;
				margin: 0;
				border-radius: 38rpx;
				margin-bottom: 16rpx;
				background: url('https://pengtou-1322587508.cos.ap-shanghai.myqcloud.com/static/images/free-purchase/free-2.png');
				background-repeat: no-repeat;
				background-size: cover;
				margin: 0 auto;
			}

			.main-loading {
				position: absolute;
				top: 50%;
				left: 50%;
				transform: translateX(-50%);
			}

			.message-list {
				box-sizing: border-box;

				// padding: 0 24rpx 0;
				.message-view {
					box-sizing: border-box;
					padding: 36rpx;

					.message-item {
						display: flex;
						width: 100%;

						.avatar {
							flex-shrink: 0;
							width: 98rpx;
							height: 98rpx;
							margin-right: 16rpx;
							border-radius: 50%;
							&.system-avatar{
								border-radius: 0;
							}
						}

						.message {
							display: flex;
							flex-direction: column;
							align-items: flex-start;
							justify-content: space-between;
							flex: 1;

							.name {
								font-size: 30rpx;
								font-weight: 900;
								color: #282D2D;
								line-height: 42rpx;
							}

							.content {
								font-size: 30rpx;
								font-weight: 400;
								color: #999B9B;
								line-height: 40rpx;
								width: calc(100vw - 98rpx - 16rpx - 36rpx * 2 - 120rpx);
							}
						}

						.statue {
							display: flex;
							flex-direction: column;
							align-items: flex-end;
							justify-content: space-between;

							.time {
								font-size: 24rpx;
								font-weight: 400;
								color: #999B9B;
								line-height: 37rpx;
							}

							.count {
								width: 34rpx;
								text-align: center;
								height: 34rpx;
								background: #FF4664;
								font-size: 22rpx;
								font-weight: 400;
								color: #FFFFFF;
								line-height: 34rpx;
								border-radius: 50%;
							}
						}
					}
				}
			}
		}
	}
</style>